package ability

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"strconv"
	"time"
)

type PingUrl struct {
	Name    string   //任务名称
	Machine string   //机器人
	Url     string   //探测地址
	People  []string //通知人列表
}

func NewPing(PingCof PingUrl) *PingUrl {
	return &PingUrl{
		Name:    PingCof.Name,
		Machine: PingCof.Machine,
		Url:     PingCof.Url,
		People:  PingCof.People,
	}
}

func (p *PingUrl) Ping() (str string, Consuming int64) {
	//记录时间
	t := time.Now()

	str = p.Get()
	t2 := time.Since(t)
	fmt.Println("任务:", p.Name, "探活耗时:", t2, "返回值:", str)

	return str, int64(t2)
}

func (p *PingUrl) Get() string {

	// 超时时间：5秒
	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Get(p.Url)
	if err != nil {
		return err.Error()
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		str := "链接探测出错 任务为," + p.Name + "\n链接为: " + p.Url + "   \n状态码为: " + strconv.Itoa(resp.StatusCode)
		DingGive(p.Machine, str, p.People)
	}
	var buffer [512]byte
	result := bytes.NewBuffer(nil)
	for {
		n, err := resp.Body.Read(buffer[0:])
		result.Write(buffer[0:n])
		if err != nil && err == io.EOF {
			break
		} else if err != nil {
			str := "链接探测出错 任务为," + p.Name + "\n链接为: " + p.Url + "\n返回错误为" + err.Error()
			DingErr(p.Machine, str)
			return err.Error()
		}
	}

	return result.String()
}
